package controllers.listeners.semrep;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;

import javax.swing.JOptionPane;

import models.SemRepFileModel;
import models.SemRepModel;
import views.MainPanel;

/* Saves to the current file loaded; allows you to choose if there is none loaded */
/* actionPerformed when you click the "Save" button */
public class SaveSemRepActionListener implements ActionListener {
	
	protected MainPanel view;
	
	public SaveSemRepActionListener() {
		view = null;
	}
	
	@Override
	public void actionPerformed(ActionEvent e) {
		save(view.getCurrentFile());
	}
	
	protected void save(File file) {
		if (file == null) {
			SemRepFileModel.setToSave(true);
			SemRepFileModel.readNewFile();
			file = SemRepFileModel.getFile();
			
			if (file == null) {
				return;
			}
		}
		
		SemRepModel.setConstituent(view.getConstituent());
		
		try {
			SemRepModel.write();
			JOptionPane.showMessageDialog(null, "Save successful!", "Success!", JOptionPane.PLAIN_MESSAGE);
		} catch (Exception ex) {
			JOptionPane.showMessageDialog(null,	"Save failed!", "Error", JOptionPane.ERROR_MESSAGE);
		}
		
		view.setCurrentFile(file);
	}
	
	public void setView(MainPanel view) {
		this.view = view;
	}
	
}
